<?php

namespace api\modules\v1\models;

use Yii;

/**
 * This is the model class for table "{{%article}}".
 *
 * @property int $id
 * @property string|null $title
 * @property int|null $uid
 * @property int|null $type
 * @property string|null $connect
 * @property int|null $status
 * @property string|null $content_short
 * @property string|null $source_uri
 * @property string|null $image_uri
 * @property int|null $display_time
 * @property int|null $comment_disabled
 * @property int|null $importance
 * @property int|null $created_at
 * @property-read mixed $user
 * @property-read string|false $updateTime
 * @property-read string|false $createTime
 * @property int|null $updated_at
 */
class Article extends BaseModel
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%article}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['type', 'status', 'display_time', 'comment_disabled', 'importance', 'uid', 'created_at', 'updated_at'], 'integer'],
            [['connect', 'content_short', 'image_uri', 'source_uri'], 'string'],
            [['title'], 'string', 'max' => 100],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id'    => 'ID',
            'uid'   => '用户ID',
            'title' => '文章标题',
            'type'  => '文章类型',
            'connect' => '文章内容',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    public function beforeSave($insert)
    {
        if ($insert) {
            $this->created_at = time();
            $this->uid = $this->loginUser->id;
        }
        $this->updated_at = time();
        return parent::beforeSave($insert); // TODO: Change the autogenerated stub
    }

    public function fields()
    {
        // return parent::fields(); // TODO: Change the autogenerated stub
        $fields =  parent::fields();

        // 关联模型
        $fields['user'] = 'user';

        // 格式化数据
        $fields['createTime'] = 'createTime';
        $fields['updateTime'] = 'updateTime';
        return $fields;
    }

    /**
     * 格式化创建时间
     * @return false|string
     */
    public function getCreateTime() {
        return date('Y-m-d H:i:s', $this->created_at);
    }

    /**
     * 格式化更新时间
     * @return false|string
     */
    public function getUpdateTime() {
        return date('Y-m-d H:i:s', $this->updated_at);
    }

    // 创建用户
    public function getUser() {
        return $this->hasOne(User::className(), ['id'=>'uid']);
    }


}
